﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint;

namespace CodeArt.SharePoint.PermissionEx
{
    public class FormFieldWithPermisison : FormField
    {
        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            SPUser currentUser = SPContext.Current.Web.CurrentUser;

            if (currentUser != null && currentUser.IsSiteAdmin)//is site admin
            {                
                return;
            }

            ListFieldPermissionSetting listSetting = ListFieldPermissionSetting.GetListSetting(this.List);
            if (listSetting == null || listSetting.Count == 0)
            {
                return;
            }                       

            SPUser author = null;

            if (this.ControlMode == SPControlMode.New)
            {
                author = base.Web.CurrentUser;
               
                FieldPermission set = listSetting.GetByFieldName(this.Field.InternalName);

                if (set != null && !set.CanEdit(currentUser, author))
                {
                    this.Visible = false;
                }               
            }
            else
            {
                SPFieldUserValue authorFieldValue = new SPFieldUserValue(base.Web, "" + this.ListItem["Author"]);
                author = authorFieldValue.User;               

                FieldPermission set = listSetting.GetByFieldName(this.Field.InternalName);

                if (set != null)
                {
                    if (!set.CanEdit(currentUser, author))
                    {
                        if (set.CanDisplay(currentUser, author))
                            this.ControlMode = SPControlMode.Display;
                        else
                            this.Visible = false;
                    }
                }                
            }            
        }
    }
}
